package db

import (
	"context"
	"log"
	"sync"

	"gitee.com/kun-ease/libra/config"
	"gitee.com/kun-ease/libra/utils"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
)

type Dao struct {
	DB *MysqlDB
}

var mysqlStore *sync.Map

type MysqlDB struct {
	Mc *gorm.DB
	Sc []*gorm.DB
}

func (m *MysqlDB) Master(ctx context.Context) *gorm.DB {
	return m.Mc
}
func (m *MysqlDB) Slaves(ctx context.Context) *gorm.DB {
	index := utils.IntRange(0, len(m.Sc))
	return m.Sc[index]
}

func Init() {
	conf := config.GetConf()
	mysqlStore = &sync.Map{}
	for _, v := range conf.Mysql {
		db := InitMysql(v)
		mysqlStore.Store(v.Name, db)
	}
}
func InitMysql(conf config.MysqlConf) (mc *MysqlDB) {
	mc = &MysqlDB{}
	var err error
	mc.Mc, err = gorm.Open(mysql.Open(conf.Master), &gorm.Config{})
	mc.Sc = []*gorm.DB{}
	for _, v := range conf.Slaves {
		smc := &gorm.DB{}
		smc, err = gorm.Open(mysql.Open(v), &gorm.Config{})
		if err != nil {
			panic(err.Error())
		}
		mc.Sc = append(mc.Sc, smc)
	}
	return
}
func GetMysqlClient(name string) *MysqlDB {
	v, ok := mysqlStore.Load(name)
	if !ok {
		log.Panicln("mysqlCon.Load err nil", name)
		return nil
	}
	db, ok := v.(*MysqlDB)
	if !ok {
		log.Panicln("mysqlCon.Load err")
		return nil
	}
	return db
}
func RegisterMysql(conf config.MysqlConf) {
	mc := InitMysql(conf)
	mysqlStore.Store(conf.Name, mc)
}
